#include "dealProcess.h"

DealProcess::DealProcess(QObject *parent) :
    QObject(parent) {

    init();
}

DealProcess::~DealProcess() {}

void DealProcess::init() {
    process = new QProcess;
    data_in.resize(0);  //将数据初始化为 0
}

QByteArray DealProcess::exec(QString command, QStringList args) {
    QByteArray res = "Process had been executed!"; //定义一个

    process -> start(command, args);    //开启一条命令执行通道

    if(!process -> waitForStarted()) {  //等待命令通道的开启
        return "Process start failed!"; //否则返回命令通道失败
    }

    if(data_in.size() != 0) {           //判断写入数据的长度是否为 0，是则跳过写入步骤
        process -> write(data_in);      //写入数据
        process -> closeWriteChannel(); //关闭数据写入通道
    }

    if(!process -> waitForFinished()) { //等待命令自行完成
        return "Process finished failed!";  //否则返回命令执行失败
    }

    data_in.resize(0);  //将数据还原为 0

    res = process -> readAll();    //接收反馈数据

    return res; //返回反馈数据
}

void DealProcess::write(QString data) {
    QByteArray byteArray;   //初始化一个 QByteArray 变量用来接收需要写入的数据

    byteArray = data.toUtf8().data();   //使用变量 byteArray 接收写入数据
    data_in.resize(byteArray.size());   //根据接收数据大小重新定义类成员变量 data_in 的大小
    data_in = byteArray;    //将变量 byteArray 接收到的数据写入到类成员变量
}
